package com.spstudio.iforward.end.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

import javax.annotation.PostConstruct;
import javax.ejb.Schedule;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.inject.Inject;

import com.spstudio.iforward.core.helper.DatabaseHelper;
import com.spstudio.iforward.core.qualifier.SPCoreLogged;
import com.spstudio.iforward.end.interfaces.ISPCoreSystemBeanRemote;

@Singleton
@Startup
public class SPCoreSystemBean implements ISPCoreSystemBeanRemote {
	
	@Inject @SPCoreLogged Logger log;
	@Inject DatabaseHelper helper;
	
	private static final String PICTURE_SAVED_PATH = "PIC_SAVED_PATH";
	private static final String PICTURE_HTTP_HOST = "PIC_HTTP_HOST";
	private static final String LOAD_CONFIG_SQL =  "select sc.key, sc.value from sys_config sc";
	
	private Map<String, String> returnMap = null;
	
	@Schedule(minute = "*/10", hour = "*", persistent = false)
	public void loadSysConfig(){
		Map<String, String> configMap = new HashMap<String, String>();
		for(Object[] object: helper.doQuery(LOAD_CONFIG_SQL, null)){
			configMap.put((String)object[0], (String)object[1]);
		}
		returnMap = configMap;
		log.info(configMap.size() + " configuration key/value loaded.");
	}
	
	@PostConstruct
	public void postConstruct(){
		loadSysConfig();
	}

	@Override
	public String retrievePictureSavePath() {
		return returnMap == null ? null : returnMap.get(PICTURE_SAVED_PATH);
	}

	@Override
	public String retrievePictureHttpHost() {
		return returnMap == null ? null : returnMap.get(PICTURE_HTTP_HOST);
	}

}
